<?php
/* Checks that data given in installation form is fine and set up new variables, database
   and such. */
$dbtype = "MySQL";
$dbhost = $_POST['dbhost'];
$dbuser = $_POST['dbuser'];
$dbpasswd = $_POST['dbpasswd'];
$dbname = $_POST['dbname'];
$current_dir = dirname(__FILE__);
$userdirs = $_POST['userdirs'];
$tbprefix = $_POST['tbprefix'];
$javapath = $_POST['javapath'];
$success =true;
include_once("./db_functions.php");
if(!db_connect()) {
  print "ERROR: unable to connect DB {$dbname} at {$dbhost}.<br />";
  $success = false;
} else {
  $r = mysql_query("create table {$tbprefix}users(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(32), passwd VARCHAR(40), lang VARCHAR(2), salt VARCHAR(8))");
}

if(! is_dir($current_dir."/tmp")) 
{
  if(! mkdir($current_dir."/tmp")) {
    print "ERROR: Can't create directory {$current_dir}/tmp - need write access to {$current_dir}<br />";
    $success = false;
  }
}  else if(! is_writable($current_dir."/tmp")) {
  print "ERROR: Must have write access to {$current_dir}/tmp<br />";
  $success = false;
}
   
if(! is_dir($userdirs)) 
{
  if(! mkdir($userdirs)) {
    $parent = explode("/",$userdirs); unset($parent[count($parent)-1]); $parent = implode("/",$parent);
    print "ERROR: Can't create user directory {$userdirs} - need write access to {$parent}<br />";
    $success = false;
  }
}  else if(! is_writable($userdirs)) {
  print "ERROR: Must have write access to {$userdirs}<br />";
  $success = false;
}

/* If everything is okay, let's generate the config file*/
   
if($success) {
  /* Build relative user dir */
  $userdirs_relative ="";
  $c = explode("/", $current_dir);
  $ud = explode("/", $userdirs);
$m = 999;
  for($i=0;$i < sizeof($c);$i++) {
    if($m == 999&&($c[$i]!=$ud[$i])) {
      $m=$i;
    }
    if($i > $m) { $userdirs_relative .= "../"; }
  }
  if($m == 999) $m = sizeof($c);
  for($m; $m < sizeof($ud); $m++) {
    if(strlen($ud[$m]) > 0)
      $userdirs_relative .= $ud[$m]."/";
  }

  $file_content = <<<TEXT
<?php

  \$dbtype = "MySQL";
  \$dbhost = "{$dbhost}";
  \$dbuser = "{$dbuser}";
  \$dbpasswd = "{$dbpasswd}";
  \$dbname = "{$dbname}";
  \$tbprefix = "{$tbprefix}";
  \$userdirs = "{$userdirs}";
  \$userdirs_relative = "{$userdirs_relative}";
  \$javapath = "{$javapath}";

?>
TEXT;

  if(is_writeable("./configuration.php")) {
    $f = fopen("./configuration.php", "w");
    fwrite($f, $file_content);
    fclose($f);
  } else {
    print "ERROR: Unable to write file configuration.php. Fix the permissions!<br />";
  }
  
}
?>


